<?php
/**
 * Created by 胡祥能 on 2018/4/11.
 *  email：huxiangneng@jiuletech.com
 */

namespace App\Http\Controllers\Admin;

use App\Helpers\Api\ApiResponse;
use App\Models\Sidebar;
use App\Permission;
use App\Role;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Log;

class RoleController extends DefaultController
{
    use ApiResponse;

    public function index(Request $request) {
        $perPage = $request->input('perPage')?:15;
//            $username = $request->input('username');
        $where = [];
//            if (!empty($username)) {
//                array_push($where, ['name', '=', $username]);
//            }

        $roles = Role::where($where)->orderBy('id', 'desc')->paginate($perPage);
        return view('admin.system.role', ['roles'=>$roles]);
    }

    public function add(Request $request)
    {
        if($request->method() == "POST"){
            $validator = Validator::make($request->all(), [
                'name' => 'bail|required|max:30',
                'display_name' => 'bail|required|max:30',
                'description' => 'max:50',
            ]);

            $name = $request->input('name');
            $res = Role::where('name', $name)->first();
            if($res){
                $validator->errors()->add('name', '已存在该角色名');
                return back()->withInput()->withErrors($validator);
            }

            $role = new Role();
            $role->name = $name;
            $role->display_name = $request->input('display_name');
            $role->description = $request->input('description');
            $role->save();

            return $this->successView('', '/roles');
        } else {
            return view('admin.system.role-add');
        }
    }

    public function update(Request $request){
        if($request->method() == "GET"){
            $id = $request->input('id');
            if(empty($id)){
                return view('admin.404');
            }

            $role = Role::find($id);
            return view('admin.system.role-update', ['role'=>$role]);
        }else{
            $validator = Validator::make($request->all(), [
                'name' => 'bail|required|max:30',
                'display_name' => 'bail|required|max:30',
                'description' => 'max:50',
            ]);
            $id = $request->input('id');
            $name = $request->input('name');
            $res = Role::where('name', $name)->where('id', '!=', $id)->first();
            if($res){
                $validator->errors()->add('name', '已存在该角色名');
                return back()->withInput()->withErrors($validator);
            }
            $role = Role::find($id);
            $role->name = $name;
            $role->display_name = $request->input('display_name');
            $role->description = $request->input('description');
            $res = $role->save();
            if($res){
                return $this->successView('', '/roles');
            }else{
                return $this->failView('', '/roles');
            }
        }
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');
        if(empty($id)){
            return $this->json(1001);
        }

        $res = Role::where('id', $id)->delete();

        if($res){
            //验证和用户、权限、菜单的关联是否与之删除
            DB::table(Sidebar::SIDEBAR_ROLE)->where('role_id', $id)->delete();
            DB::table('permission_role')->where('role_id', $id)->delete();
            DB::table('role_user')->where('role_id', $id)->delete();

            return $this->json(200);
        }else{
            return $this->json(1002);
        }
    }

    public function assign(Request $request){

        if($request->method() == 'POST'){
            $id = $request->input('id');
            if(empty($id)){
                return $this->failView('缺少参数');
            }

            $assignPerssions = DB::table('permission_role')
                ->where('roles.id', $id)
                ->leftJoin('roles','roles.id','=','permission_role.role_id')
                ->get();
            $assign_ids = [];
            foreach ($assignPerssions as $item) {
                array_push($assign_ids, $item->id);
            }

            $roles = $request->input('assign-permissions')?:[];
            $diff1 = array_diff($assign_ids, $roles);//需要删除的权限id
            $diff2 = array_diff($roles, $assign_ids);//需要增加的权限id

            if($diff1){
                foreach ($diff1 as $v){
                    DB::table('permission_role')->where('role_id', $id)->where('permission_id', (int)$v)->delete();
                }
            }

            if($diff2){
                foreach ($diff2 as $item){
                    DB::table('permission_role')->insert([
                        'role_id'=> $id,
                        'permission_id'=> (int)$item
                    ]);
                }
            }

            return $this->successView('', '/roles');
        }else{
            $id = $request->input('id');
            if(empty($id)){
                return $this->failView('缺少参数');
            }

            $role = Role::find($id);
            $assignPerssions = DB::table('permission_role')
                ->where('permission_role.role_id', $id)
                ->leftJoin('permissions','permissions.id','=','permission_role.permission_id')
                ->get();
            $assign_ids = [];
            foreach ($assignPerssions as $item) {
                array_push($assign_ids, $item->id);
            }

            $permissions = Permission::all();
            foreach ($permissions as &$val){
                $val->selected = (in_array($val->id, $assign_ids))?true:false;
            }
            return view('admin.system.role-assign', ['role'=>$role, 'permissions' => $permissions]);
        }
    }
}